package com.navinfo.app.hd

import android.util.Log
import com.navinfo.collect.library.data.NavinfoPbfData
import com.navinfo.collect.library.data.RealmUtils
import com.navinfo.collect.library.data.entity.LayerEntity
import com.navinfo.collect.library.utils.GeometryTools
import io.realm.Realm
import me.rosuh.filepicker.config.FilePickerManager
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.LineString
import org.locationtech.jts.operation.buffer.BufferParameters
import java.io.File
import java.io.FileInputStream
import java.util.HashMap
import java.util.function.Predicate

class PbfDataImport {
    private val NAME = "name"
    private val TYPE = "navi_type"

    fun importPbfData() {
        val files = FilePickerManager.obtainData()
        Log.d("MainActivity：", "用户选中的文件是$files")
//                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).where(GeometryFeatureEntity::class.java).findFirst()
        if (files.isNullOrEmpty()) {
//            Toast.makeText(this@MainActivity, "没有选中任何文件", Toast.LENGTH_SHORT).show()
        } else {
//            loadingDialog.show()
            // 开启线程插入数据
            object: Thread() {
                override fun run() {
                    super.run()
                    Log.d("Realm-file:", files.size.toString())
                    // 用户选中了对应的pbf数据
                    val startTime = System.currentTimeMillis()
                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).beginTransaction()
                    for (file in files) {
                        Log.d("Realm-file:", file)
                        print("file:"+file)
                        val resultData = NavinfoPbfData.readPbfData(FileInputStream(File(file)))
                        // 数据插入时间统计
                        val sqlStartTime = System.currentTimeMillis()

                        if (resultData.hadlanelinkList.isNotEmpty()) { // 解析车道中心线
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "车道中心线";
                            extentMap[TYPE] = "had_lane_link";
                            for (hadLaneLink in resultData.hadlanelinkList) {
                                val geometry = NavinfoPbfData.createGeometry(hadLaneLink.geometry)
                                // 转换geometry和属性信息为数据库字段
                                val geometryEntity =
                                    NavinfoPbfData.createGeometryEntity(geometry, hadLaneLink.allFields, extentMap)
                                geometryEntity.layerEntity = layerEntity
                                geometryEntity.name = extentMap[NAME]
                                // 保存数据到sqlite
                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)
                            }
                        }
                        if (resultData.hadlanemarklinkList.isNotEmpty()) { // 解析车道边线
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "车道边线";
                            extentMap[TYPE] = "had_lane_mark_link";
                            // 处理车道边线的渲染字段
                            for (hadLaneMarkLink in resultData.hadlanemarklinkList) {
                                val geometry = NavinfoPbfData.createGeometry(hadLaneMarkLink.geometry)
                                for (boundary in hadLaneMarkLink.boundaryList) {
                                    val sPoint = boundary.paPosition.sIndex
                                    val ePoint = boundary.paPosition.eIndex
                                    // 从link的geometry中截取该段boundary的线段,使用起终点构建的buffer矩形切割geometry
                                    val line = GeometryTools.getLineStrinGeo(
                                        arrayOf(
                                            Coordinate(sPoint.latLon.longitudeDegrees, sPoint.latLon.latitudeDegrees, sPoint.elevation.z),
                                            Coordinate(ePoint.latLon.longitudeDegrees, ePoint.latLon.latitudeDegrees, ePoint.elevation.z)
                                        )
                                    )
                                    val bufferLine = line.buffer(1e-7, 1, BufferParameters.CAP_FLAT)
                                    val boundaryGeometry = geometry.intersection(bufferLine)
                                    extentMap.remove("boundary_type")
                                    extentMap.remove("mark_type")
                                    extentMap.remove("mark_color")
                                    extentMap.remove("mark_material")
                                    extentMap.remove("mark_width")
                                    if (boundary.boundaryType!=null) {
                                        extentMap["boundary_type"] = boundary.boundaryType.type.toString()
                                        if (boundary.boundaryType.type == 2 && boundary.markingList!=null&&boundary.markingList.isNotEmpty()) {
                                            extentMap["mark_type"] = boundary.markingList[0].markType.toString()
                                            extentMap["mark_color"] = boundary.markingList[0].markColor.toString()
                                            extentMap["mark_material"] = boundary.markingList[0].markMaterial.toString()
                                            extentMap["mark_width"] = boundary.markingList[0].markWidth.toString()
                                        }
                                    }
                                    // 转换geometry和属性信息为数据库字段
                                    val geometryEntity =
                                        NavinfoPbfData.createGeometryEntity(boundaryGeometry, boundary.allFields, extentMap)
                                    geometryEntity.layerEntity = layerEntity
                                    geometryEntity.name = extentMap[NAME]
                                    // 保存数据到sqlite
                                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)
                                }
                            }
                        }
                        if (resultData.objectarrowList.isNotEmpty()) { // 解析道路箭头
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "道路箭头";
                            extentMap[TYPE] = "object_arrow";
                            for (objectArrow in resultData.objectarrowList) {
                                val geometry = NavinfoPbfData.createGeometry(objectArrow.geometry)
                                // 转换geometry和属性信息为数据库字段
                                val geometryEntity =
                                    NavinfoPbfData.createGeometryEntity(geometry, objectArrow.allFields, extentMap)
                                geometryEntity.layerEntity = layerEntity
                                geometryEntity.name = extentMap[NAME]
                                // 保存数据到sqlite
                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)

                                // 当前箭头与tile内laneLink数据相交计算
                                m@ for (lanLinkPid in objectArrow.lanePidList) {
                                    for (lanLink in resultData.hadlanelinkList) {
                                        if (lanLinkPid.equals(lanLink.laneLinkPid)) {
                                            val lanLinkGeometry = NavinfoPbfData.createGeometry(lanLink.geometry)
                                            if (lanLinkGeometry.intersects(geometry)) {
                                                val intersection = geometry.intersection(lanLinkGeometry)
                                                if (intersection.isValid&&!intersection.isEmpty&&intersection is LineString) {
                                                    val extentMap = HashMap<String, String>()
                                                    extentMap[TYPE] = "symbol_object_arrow"
                                                    extentMap[NAME] = "symbol_object_arrow"
                                                    extentMap["arrow_class"] = objectArrow.arrowClass.toString()
                                                    // 判断箭头的首尾排序
                                                    val geometryEntity =
                                                        NavinfoPbfData.createGeometryEntity(intersection, null, extentMap)
                                                    geometryEntity.layerEntity = layerEntity
                                                    geometryEntity.name = extentMap[NAME]
                                                    // 保存数据
                                                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)
                                                }
                                                break@m
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (resultData.objectcrosswalkList.isNotEmpty()) { // 解析人行横道
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "人行横道";
                            extentMap[TYPE] = "object_crosswalk";
                            for (objectCross in resultData.objectcrosswalkList) {
                                val geometry = NavinfoPbfData.createGeometry(objectCross.geometry)
                                // 转换geometry和属性信息为数据库字段
                                val geometryEntity =
                                    NavinfoPbfData.createGeometryEntity(geometry, objectCross.allFields, extentMap)
                                geometryEntity.layerEntity = layerEntity
                                geometryEntity.name = extentMap[NAME]
                                // 保存数据到sqlite
                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)
                            }
                        }
                        if (resultData.objectpoleList.isNotEmpty()) { // 解析杆状物
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "杆状物";
                            extentMap[TYPE] = "object_pole";
                            val extentMap3D = HashMap<String, String>()
                            extentMap3D[TYPE] = "symbol_object_pole";
                            extentMap3D[NAME] = "symbol_object_pole";
                            for (objectPole in resultData.objectpoleList) {
                                val geometry = NavinfoPbfData.createGeometry(objectPole.geometry)
//                                // 转换geometry和属性信息为数据库字段
//                                val geometryEntity =
//                                    NavinfoPbfData.createGeometryEntity(geometry.centroid, objectPole.allFields, extentMap)
//                                geometryEntity.layerEntity = layerEntity
//                                geometryEntity.name = extentMap[TYPE]
//                                // 保存数据到sqlite
//                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)

                                // 转换geometry和属性信息为数据库字段
                                val symbolEntity =
                                    NavinfoPbfData.createGeometryEntity(geometry.centroid, objectPole.allFields, extentMap3D)
                                symbolEntity.layerEntity = layerEntity
                                symbolEntity.name = extentMap3D[NAME]
                                // 保存数据到sqlite
                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(symbolEntity)
                            }
                        }
                        if (resultData.objectsymbolList.isNotEmpty()) { // 解析对象标志
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "对象标志";
                            extentMap[TYPE] = "object_symbol";

                            val extentMap3D = HashMap<String, String>()
                            extentMap3D[NAME] = "symbol_object_symbol";
                            extentMap3D[TYPE] = "symbol_object_symbol";
                            for (objectSymbol in resultData.objectsymbolList) {
                                val geometry = NavinfoPbfData.createGeometry(objectSymbol.geometry)
//                                // 转换geometry和属性信息为数据库字段
//                                val geometryEntity =
//                                    NavinfoPbfData.createGeometryEntity(geometry, objectSymbol.allFields, extentMap)
//                                geometryEntity.layerEntity = layerEntity
//                                geometryEntity.name = extentMap[NAME]
//                                // 保存数据到sqlite
//                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)

                                // 转换geometry和属性信息为数据库字段
                                val symbolEntity =
                                    NavinfoPbfData.createGeometryEntity(geometry.centroid, null, extentMap3D)
                                symbolEntity.layerEntity = layerEntity
                                symbolEntity.name = extentMap3D[NAME]
                                // 保存数据到sqlite
                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(symbolEntity)
                            }
                        }
                        if (resultData.objecttrafficlightsList.isNotEmpty()) { // 解析交通灯
                            val layerEntity: LayerEntity = LayerEntity()
                            layerEntity.layerName = "test"
                            val extentMap = HashMap<String, String>()
                            extentMap[NAME] = "交通灯";
                            extentMap[TYPE] = "object_traffic";

                            val extentMap3D = HashMap<String, String>()
                            extentMap3D[TYPE] = "symbol_object_traffic";
                            extentMap3D[NAME] = "symbol_object_traffic";
                            for (objectTrrafic in resultData.objecttrafficlightsList) {
                                val geometry = NavinfoPbfData.createGeometry(objectTrrafic.geometry)
//                                // 转换geometry和属性信息为数据库字段
//                                val geometryEntity =
//                                    NavinfoPbfData.createGeometryEntity(geometry, objectTrrafic.allFields, extentMap)
//                                geometryEntity.layerEntity = layerEntity
//                                geometryEntity.name = extentMap[NAME]
//                                // 保存数据到sqlite
//                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(geometryEntity)

                                // 转换geometry和属性信息为数据库字段
                                val symbolEntity =
                                    NavinfoPbfData.createGeometryEntity(geometry.centroid, null, extentMap3D)
                                symbolEntity.layerEntity = layerEntity
                                symbolEntity.name = extentMap3D[NAME]
                                // 保存数据到sqlite
                                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(symbolEntity)
                            }
                        }
                        val sqlEndTime = System.currentTimeMillis()
                        System.out.println(file+"All-Time:"+(sqlEndTime-sqlStartTime))
                    }
                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).commitTransaction()
                    val endTime = System.currentTimeMillis()
                    System.out.println("All-Time:"+(endTime-startTime))

                    Realm.compactRealm(RealmUtils.getInstance().realmConfiguration)
                    System.out.println("Arrow-All-Time: 数据处理结束")
                }
            }.start()

        }
    }
}